//
//  FeedItemsViewController.m
//  Feeder
//
//  Created by Diego Acosta on 9/3/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "FeedItemsViewController.h"
#import "EGORefreshTableHeaderView.h"
#import "UserDefaultsHelper.h"
#import "GoogleReader.h"
#import "FormatHelper.h"
#import "FeedItemTableViewCell.h"
#import "ReadItemViewController.h"

#define kFeedItemCellHeight 78


@interface FeedItemsViewController(Private)

- (void)_setupBackButton;

- (void)_getFeedItems;

- (void)_configureRefreshHeaderView;
- (void)_reloadTableViewDataSource;
- (void)_doneLoadingTableViewData;
- (void)_dataSourceDidFinishLoadingNewData;

@end

@implementation FeedItemsViewController

@synthesize feedid;
@synthesize feedinfo;

#pragma mark -
#pragma mark View lifecycle

- (void)viewDidLoad {
	
    [super viewDidLoad];

	// format title.
	NSString * title = [FormatHelper stringFormatForTitle:[feedinfo objectForKey:@"title"]
										  withUnreadCount:[feedinfo objectForKey:@"count"]];
	// view title.
	self.navigationItem.title = title;
	
	// set table cell height.
	self.tableView.rowHeight = kFeedItemCellHeight;
	
	// configure refresh header view.
	[self _configureRefreshHeaderView];
	
	// get all data.
	[self _getFeedItems];
}

/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/

/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/

/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
*/

/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UI// get credentials.
 NSString * auth = [UserDefaultsHelper auth];InterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

#pragma mark -
#pragma mark Private methods

- (void)_setupBackButton {
	
	// override the navbar back button title to remove the unread items number.
	UIBarButtonItem * backButton = [[UIBarButtonItem alloc] initWithTitle:[feedinfo objectForKey:@"title"]
																	style:UIBarButtonItemStyleBordered
																   target:nil
																   action:nil];
	
	[self.navigationItem setBackBarButtonItem:backButton];
	[backButton release];
}

- (void)_getFeedItems {
	
	// get credentials.
	NSString * auth = [UserDefaultsHelper auth];
	
	// init resources.
	if (reader == nil) {
		
		reader = [[GoogleReader alloc] initWithAuth:auth];
		[reader setDelegate:self];
	}
	
	// get feed items.
	[reader getItemsForFeed:feedid];
}

- (void)_configureRefreshHeaderView {

	if (refreshHeaderView == nil) {
		
		// define header rect.
		CGRect frame = CGRectMake(0.0f,
								  0.0f - self.tableView.bounds.size.height,
								  320.0f,
								  self.tableView.bounds.size.height);
		
		refreshHeaderView = [[EGORefreshTableHeaderView alloc] initWithFrame:frame];
		refreshHeaderView.backgroundColor = [UIColor colorWithRed:226.0/255.0 green:231.0/255.0 blue:237.0/255.0 alpha:1.0];
		
		self.tableView.showsVerticalScrollIndicator = YES;
		
		// add header view into table.
		[self.tableView addSubview:refreshHeaderView];
		[refreshHeaderView release];
	}
}

- (void)_reloadTableViewDataSource {
	
	//  should be calling your tableviews model to reload
	//  put here just for demo
	[self performSelector:@selector(_doneLoadingTableViewData) withObject:nil afterDelay:3.0];
}

- (void)_doneLoadingTableViewData {
	
	//  model should call this when its done loading
	[self _dataSourceDidFinishLoadingNewData];
}

- (void)_dataSourceDidFinishLoadingNewData {
	
	_reloading = NO;
	
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:.3];
	
	[self.tableView setContentInset:UIEdgeInsetsMake(0.0f, 0.0f, 0.0f, 0.0f)];
	
	[UIView commitAnimations];
	
	[refreshHeaderView setState:EGOOPullRefreshNormal];
	[refreshHeaderView setCurrentDate];  //  should check if data reload was successful 
}

#pragma mark -
#pragma mark UIScrollViewDelegate methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {	
	
	if (scrollView.isDragging) {
		
		if (refreshHeaderView.state == EGOOPullRefreshPulling &&
			scrollView.contentOffset.y > -65.0f &&
			scrollView.contentOffset.y < 0.0f &&
			!_reloading) {
			
			[refreshHeaderView setState:EGOOPullRefreshNormal];
			
		}
		else if (refreshHeaderView.state == EGOOPullRefreshNormal &&
				   scrollView.contentOffset.y < -65.0f &&
				   !_reloading) {
			
			[refreshHeaderView setState:EGOOPullRefreshPulling];
		}
	}
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
	
	if (scrollView.contentOffset.y <= - 65.0f && !_reloading) {
		
		_reloading = YES;
		
		[self _reloadTableViewDataSource];
		[refreshHeaderView setState:EGOOPullRefreshLoading];
		
		[UIView beginAnimations:nil context:NULL];
		[UIView setAnimationDuration:0.2];
		
		self.tableView.contentInset = UIEdgeInsetsMake(60.0f, 0.0f, 0.0f, 0.0f);
		
		[UIView commitAnimations];
	}
}

#pragma mark -
#pragma mark UITableViewDataSource methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

	// if feeds is nil, we've not pulled the feeds from the backend yet.
	if (feeditems != nil) {
		
		// get items for current feed.
		NSArray * items = [feeditems objectForKey:@"items"];
		
		return [items count];
	}
	
    return 0;
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString * cellIdentifier = @"FeedItemCell";
	FeedItemTableViewCell * cell;
    
	cell = (FeedItemTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
		
		// .xib top-level objects.
        NSArray * obj = [[NSBundle mainBundle] loadNibNamed:@"FeedItemTableViewCell"
													  owner:self
													options:nil];
		
		// keep the first object (custom cell).
		cell = [obj objectAtIndex:0];
		
		// set-up once.
		cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
	
	// get items for current feed.
	NSArray * items = [feeditems objectForKey:@"items"];
	
	// get current feed item.
	NSDictionary * item = [items objectAtIndex:indexPath.row];
    
	// format title on case some html entities are coming inside.
	NSString * title = [FormatHelper convertHTMLEntiesInString:[item objectForKey:@"title"]];
	
	// format author string to show 'by' prefix.
	NSString * author = [NSString stringWithFormat:@"by %@", [item objectForKey:@"author"]];
	
	// here's the html without format to be shown on the detail label.
	NSString * detail = [item objectForKey:@"detail"];
	
	// format feed date.
	NSString * date = [FormatHelper feedDateFromUnixTime:[item objectForKey:@"published"]];
	
    // customize cell.
	cell.title.text = title;
	cell.author.text = author;
	cell.detail.text = detail;
	cell.date.text = date;
	
	// default detail text alignment.
	[cell.detail alignTop];
    
    return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark -
#pragma mark UITableViewDelegate methods

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	
	// get items for current feed.
	NSArray * items = [feeditems objectForKey:@"items"];
	
	// item to show on read view.
	NSDictionary * item = [items objectAtIndex:indexPath.row];
	
	ReadItemViewController * rivc = [[ReadItemViewController alloc] initWithNibName:@"ReadItemView"
																			 bundle:nil];
	
	// pass data to next view.
	rivc.feeditem = item;
	
	// remove unread-count from back button title.
	[self _setupBackButton];
	
	// push view.
	[self.navigationController pushViewController:rivc animated:YES];
	[rivc release];
}

#pragma mark -
#pragma mark GoogleReaderDelegate methods

- (void)requestFinished {
	
	// we'll save locally only the items for the current feed.
	feeditems = [[reader.feeditems objectForKey:feedid] copy];
	
	// reload data.
	[self.tableView reloadData];
}

- (void)requestWillStartWithAction:(RequestAction)action {

	return;
}

#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}

- (void)dealloc {

	[feedid release];
	[feedinfo release];
	[reader release];
	[feeditems release];
    [super dealloc];
}

@end

